package com.hevs.samplewebapp.server;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;

import com.google.appengine.api.datastore.Key;
import com.hevs.samplewebapp.server.entities.MedicalRecord;
import com.hevs.samplewebapp.server.entities.User;
import com.hevs.samplewebapp.server.json.ObjectMapperFactory;
import com.hevs.samplewebapp.server.service.MedicalRecordService;
import com.hevs.samplewebapp.server.service.UserService;
import com.hevs.samplewebapp.server.util.CredentialValidator;

/**
 * 
 * @author Arnaud Durand creation : 12.03.12
 * 
 *         Goal: RESTful service used by doctors for patient's Medical Records
 *         management.
 * 
 */
public class MedicalRecordSupervisorDeleteServlet extends SessionAuthHttpServlet {

	private static final long serialVersionUID = 870866277965499216L;

	public static MedicalRecordService medicalRecordService;
	{
		medicalRecordService = new MedicalRecordService();
	};
	
	public static UserService userService;
	{
		userService = new UserService();
	};

	public MedicalRecordSupervisorDeleteServlet() {
		super(2);

		setGenericCustomValidation(new CredentialValidator() {

			@Override
			public boolean hasAccess(HttpServletRequest req,
					int requiredCredentialLevel) {
				HttpSession session = req.getSession(false);
				Key localUserKey;
				User remote;
				try {
					localUserKey = (Key) session.getAttribute("userKey");
					String userMail = req.getPathInfo().replace("/", "");
					remote = userService.getUserByMail(userMail);
					if (remote == null) {
						return false;
					}

				} catch (Exception e) {
					return false;
				}
				for (Key remoteUserKey : remote.getGrantedUsers()) {
					if (localUserKey.equals(remoteUserKey))
						return true;
				}
				return false;
			}
		});
	}

	@Override
	protected void doSecurePost(HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {

		try {
			BufferedReader reader = req.getReader();
			StringBuilder sb = new StringBuilder();
			String line = reader.readLine();
			while (line != null) {
				sb.append(line + "\n");
				line = reader.readLine();
			}
			reader.close();
			System.out.println(sb.toString());

			ObjectMapper mapper = ObjectMapperFactory.get();
			MedicalRecord medicalRecord = mapper.readValue(sb.toString(),
					MedicalRecord.class);

			if (medicalRecord == null || medicalRecord.getKey() == null) {
				resp.sendError(400);
				return;
			}

			medicalRecordService.removeMedicalRecord(medicalRecord);

		} catch (Exception e) {
			e.printStackTrace();
			throw new ServletException(e);
		}
	}

	

}
